import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {Question} from "../../question";
import {TrainingService} from "../../my-service/training.service";
import {UtilService} from "../../my-service/util.service";
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-answer',
  templateUrl: './answer.component.html',
  styleUrls: ['./answer.component.css'],
})
export class AnswerComponent implements OnInit {
  trainingID: string;//训练的ID
  userGuid: string;//用户的Guid
  answerCardID: string;//答题卡ID
  questions: any;
  currentQuestionIndex = 0;//还没有做的题的最近索引
  radioValue: any;
  score = 0;// 尤金测试的成绩
  Content = [];//答题卡content
  positionBase = 33.3; //图片需要移动的基数
  answerCoverIndex = 0;
  isSingle = true;//当前的选项类型
  multiplyBoxHeight: number;
  selectMultiply = 0;

  constructor(private trainingService: TrainingService,
              private router: Router,
              private routerInfo: ActivatedRoute,
              private utilService: UtilService,
              private msg: NzMessageService,) {
    this.questions = [];

  }

  /*获取试卷题目*/
  getQuestions() {
    this.trainingService.getQuestionByPaperId().then(res => {
      if (res.status == 1) {
        res.data.forEach(val => {
          //获取单选题
          if (val.Type == 'single') {
            let question = new Question(val.PK_QuestionGuid, val.Index, val.Content, val.Status);
            let arr = val.Option.substring(1, val.Option.length - 1); //去除首尾的双引号
            let options = JSON.parse(arr);
            let i = 0;
            let num;
            options.forEach(o => {
              if (i == 0) num = 'A:';
              else if (i == 1) num = 'B:';
              else num = 'C:';
              question.addOption(o.content, o.score, num);
              i++;
            });
            this.questions.push(question);
          } else {
            let question = new Question(val.PK_QuestionGuid, val.Index, val.Content, val.Status);
            let arr = val.Option.substring(1, val.Option.length - 1); //去除首尾的双引号
            let options = JSON.parse(arr);
            let i = 0;
            question.isMultiple = true;
            options.forEach(o => {
              question.addMultipleOption(o.content, o.score, i, false);
              i++
            });
            this.questions.push(question);
          }

        });
      }
    })
  }

  /*获取答题卡，如果用户没有答题卡就去创建一个答题卡*/
  getAnswerCard(trainingID, userID) {
    this.trainingService.getCard(trainingID, userID).then(res => {
      if (res.status == 1) {
        if (res.data[0]) {
          //有答题卡
          this.answerCardID = res.data[0].PK_AnwserCardGuid;
          if (res.data[0].Content) {
            this.Content = JSON.parse(res.data[0].Content);
            this.currentQuestionIndex = this.Content[this.Content.length - 1].index + 1;
            if (this.currentQuestionIndex == 39) {
              this.isSingle = false;
            }
            if (this.currentQuestionIndex == 40) {
              //已经答完题了直接到查看结果的页面
              this.router.navigate(['../result', {
                cardID: this.answerCardID,
                id: this.trainingID
              }], {relativeTo: this.routerInfo});
            }
          }
          if (res.data[0].Score) {
            this.score = parseInt(res.data[0].Score); //获取答题卡成绩
          }
        } else {
          //没有答题卡，创建答题卡
          this.trainingService.createCard(trainingID, userID).then(res => {
            if (res.status == 1) {
              this.answerCardID = res.data;
            }
          });
        }
      }
    })
  }

  /*更新答题卡*/
  updateAnwserCard(content, score) {
    this.trainingService.updateCardByID(this.answerCardID, content, score).then(res => {
      if (res.status == 1) {
        this.currentQuestionIndex += 1;
        if (this.currentQuestionIndex == 39) {
          this.isSingle = false;
        }
        this.radioValue = null;
        if (this.currentQuestionIndex == 40) {
          this.updateFinish();
          this.router.navigate(['../result', {
            cardID: this.answerCardID,
            id: this.trainingID
          }], {relativeTo: this.routerInfo});
        }
      }
    })
  }

  /*更新答题卡完成状态*/
  updateFinish() {
    this.trainingService.updateFinishById(this.answerCardID).then(res => {
      if (res.status == 1) {
      }
    })
  }

  ngOnInit() {
    this.multiplyBoxHeight = window.document.body.clientHeight - 280;
    this.trainingID = this.routerInfo.snapshot.params.ID;
    this.answerCardID = this.routerInfo.snapshot.params.answerID;
    if (!this.answerCardID) {
      //非匿名测试
      this.utilService.getUserInfo().then(res => {
        if (res.status == 1) {
          this.userGuid = res.userGuid;
          this.getAnswerCard(this.trainingID, this.userGuid);
        }
      });
    }
    this.getQuestions();
  }

//  选择答案
  selectAnwser() {
    if (this.isSingle) {
      //单选
      if (this.radioValue) {
        //切换背景图片
        if (this.currentQuestionIndex == 38) {
          this.answerCoverIndex = 3;
        } else {
          this.answerCoverIndex++;
          if (this.answerCoverIndex > 3) {
            this.answerCoverIndex = 0;
          }
        }
        //写入答题卡
        let grade = this.questions[this.currentQuestionIndex].options[this.radioValue].grade;//获取当前这题的成绩
        let cardContent = {
          questionGuid: this.questions[this.currentQuestionIndex].id,
          selectedOptionIndex: this.radioValue,
          index: this.currentQuestionIndex
        };
        this.Content[this.currentQuestionIndex] = cardContent; //记录当前答题位置以及选项
        //判断当前题目是属于哪种类型的
        this.score += grade;
      } else {
        //没有进行选择的时候
        this.msg.warning('请您先选择答案然后再点击下一题');
        return;
      }
    } else {
      //多选，最后一题
      if (this.selectMultiply > 10) {
        this.msg.error(`该题目最多允许选10个选项，您多选了${this.selectMultiply - 10}个选项,请您修改后再进行提交`);
        return;
      } else if (this.selectMultiply < 10) {
        this.msg.error(`该题目最多允许选10个选项，您还差${-(this.selectMultiply - 10)}个选项,请您修改后再进行提交`);
        return;
      } else {
        let grade = 0;
        let i = 0;
        let selectArr = [];//记录所选的选项
        this.questions[this.currentQuestionIndex].options.forEach(o => {
          i++;
          if (o.checked) {
            grade += o.grade;
            selectArr.push(i);
          }
        });//计算多选的成绩
        this.score += grade;
        let cardContent = {
          questionGuid: this.questions[this.currentQuestionIndex].id,
          selectedOptionIndex: selectArr,
          index: this.currentQuestionIndex
        };
        this.Content[this.currentQuestionIndex] = cardContent;
      }
    }
    //更新答题卡
    this.updateAnwserCard(this.Content, this.score);
  }

  //当进行多选时
  selectMultipleOptions(event) {
    if (this.selectMultiply >= 10 && event) {
      this.msg.warning('该题目最多允许选10个选项，请勿进行多选');
    }
    if (event) {
      this.selectMultiply += 1;
    } else {
      this.selectMultiply -= 1;
    }

  }

}
